import EventTarget from './EventTarget'
import StyleGenerator from './StyleGenerator'
class Node extends EventTarget {
	constructor(name) {
		super()
		this.name = name || ''
		this.points = []
		this.parent = null
		this.children = []
		this.center = []
		this.dirty = false
		new StyleGenerator(this)
	}
	compute(){
		for(let name in this.style){
			let val = this.style[name]
			if(this.parent.tag === 'world'){
				if(name === 'width' || name === 'height') {
					val = parseInt(val)
					if(!(val > 0))  val = this.parent[name]
				}
			}
			this.style[name] = val
		}
	}
	setStyle(style){
		if(typeof(style) === 'object'){
			for(let name in style){
				this.style[name] = style[name]
			}
		}
	}
	getClient() {
		let parent = this.parent,
			points = [],
			x = this.props.x,
			y = this.props.y
		while (parent) {
			if (parent.props) {
				x += parent.props.x
				y += parent.props.y
			}
			parent = parent.parent
		}
		points.push(
			[x, y],
			[x + this.props.width, y],
			[x + this.props.width, y + this.props.height],
			[x, y + this.props.height]
		)
		return points
	}
	removeChild(child) {
		let i = 0, len = this.children.length;
		if(child instanceof Node){
			for (; i < len; i++) {
				if (this.children[i] === child) {
					this.children.splice(i, 1)
					break;
				}
			}
		}else if(typeof(child) === 'string'){
			let els = this.find(child)
			els.forEach(child => {
				for (i=0; i < len; i++) {
					if (this.children[i] === child) {
						this.children.splice(i, 1)
						break;
					}
				}
			})
		}
	}
	remove(){
		if(this.parent) this.parent.removeChild(this)
	}
	clear() {
		this.children.splice(0, this.children.length)
	}
	find(name){
		let arr = []
		if(typeof(name) === 'string'){
			for(let len = 0, i = 0; i<len; i++){
				if(this.children[i].name === name){
					arr.push(this.children[i])
				}else{
					let sub = this.children[i].find(name)
					if(sub && sub[0]) arr.push(sub[0])
				}
			}
		}
		return arr
	}
}

export default Node